# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

import django
from django import http
from django import shortcuts
from django import template

from models import Track

import myforms
import tchelper
import cruncher
import users

def respond(request, user, template, params=None):
  if params is None:
    params = {}
  if user:
    params['user'] = user
  if not template.endswith('.html') and not template.endswith('.css'):
    template += '.html'
  params['path'] = request.path
  return shortcuts.render_to_response(template, params)

def redirect(request, path):
	return respond(request, None, 'redirect', {'redirect_path':path})
	
def css(request):
	return respond(request, None, 'site.css', {})

def index(request):
	mykey = request.GET.get("mykey")
	compareform = myforms.CompareLibrariesForm({'key1':mykey, 'key2':''})
	return respond(request, None, 'index', {'compareform':compareform, 'compareaction':request.path+"compare", 'createkeyaction':request.path+"createkey"})
	
def createkey(request):
	uploadform = myforms.UploadFileForm()
	return respond(request, None, 'createkey', {'uploadform': uploadform, 'uploadaction':"/tc/upload"})
	
def upload(request):
	from tchelper import UploadProgressCachedHandler
	from tchelper import TracksFromFile
	request.upload_handlers.insert(0, UploadProgressCachedHandler(request))
	user = None
	file = None
	
	if 'file' in request.FILES:
		file = request.FILES['file']
	else:
		return redirect(request, "/tc/createkey")

	if tchelper.validate_itunes_library_file(file):
		uploadform = myforms.UploadFileForm()
		user = users.getUser(None)
		eatFile = TracksFromFile(file, user.key)
		eatFile.start()
		return redirect(request, "/tc?mykey="+user.key);
	else:	
		return respond(request, user, 'invalid', {'name':file.name})
		
from django.core.cache import cache

def compare(request):
	
	compareform = myforms.CompareLibrariesForm(request.POST)
	if compareform.is_valid():
		key1 = compareform.cleaned_data['key1']
		key2 = compareform.cleaned_data['key2']
		user1 = users.getUser(key1)
		user2 = users.getUser(key2)
		if user1 is None or user2 is None:
			return respond(request, None, 'analyzing', {'crunchresult':"One of the keys you requested does not exist! Please double check it and try again."})
		if cache.get(key1) or cache.get(key2):
			return respond(request, None, 'analyzing', {'crunchresult':"One of the keys you requested is still being processed. Try again in a few minutes."})
		tl1 = list(Track.objects.filter(user=key1))
		tl2 = list(Track.objects.filter(user=key2))
		crunchstring = str(cruncher.percentArtistOverlap(tl1,tl2)) +" percent of your artists also appear in the other library"
		return respond(request, None, 'analyzing', {'crunchresult':crunchstring})
		
	return respond(request, None, 'analyzing', {'crunchresult':"An error occured"})
	

from django.core.cache import cache
from django.http import HttpResponse, HttpResponseServerError 

def upload_progress(request):
    """
    Return JSON object with information about the progress of an upload.
    """
    progress_id = ''
    if 'X-Progress-ID' in request.GET:
        progress_id = request.GET['X-Progress-ID']
    elif 'X-Progress-ID' in request.META:
        progress_id = request.META['X-Progress-ID']
    if progress_id:
        from django.utils import simplejson
        cache_key = progress_id
        data = cache.get(cache_key)
        return HttpResponse(simplejson.dumps(data))
    else:
        return HttpResponseServerError('Server Error: You must provide X-Progress-ID header or query param.')
	
	
